package com.zhss.eshop.order.state;

import com.zhss.eshop.order.constant.OrderStatus;
import com.zhss.eshop.order.domain.dto.OrderInfoDTO;
import com.zhss.eshop.order.state.states.CanceledOrderState;
import com.zhss.eshop.order.state.states.DefaultOrderState;
import com.zhss.eshop.order.state.states.WaitForPayOrderState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 订单状态管理器
 * @author suyuan
 *
 */
@Component
public class OrderStateManagerImpl implements OrderStateManager {

	/**
	 * 待付款状态
	 */
	@Autowired
	private WaitForPayOrderState waitForPayOrderState;
	/**
	 * 已取消状态
	 */
	@Autowired
	private CanceledOrderState canceledOrderState;

	/**
	 * 默认状态
	 */
	@Autowired
	private DefaultOrderState defaultOrderState;

	/**
	 * 创建订单
	 * @param order 订单
	 * @throws Exception
	 */
	@Override
	public void create(OrderInfoDTO order) throws Exception {
		waitForPayOrderState.doTransition(order);
	}

	/**
	 * 订单能否执行取消操作
	 * @param order 订单
	 * @return 能否执行取消操作
	 * @throws Exception
	 */
	@Override
	public Boolean canCancel(OrderInfoDTO order) throws Exception {
		return getOrderState(order).canCancel(order);
	}

	/**
	 * 执行取消订单操作
	 * @param order 订单
	 * @throws Exception
	 */
	@Override
	public void cancel(OrderInfoDTO order) throws Exception {
		canceledOrderState.doTransition(order);
	}




	/**
	 * 获取订单状态组件
	 * @param order 订单
	 * @return 订单状态组件
	 * @throws Exception
	 */
	private OrderState getOrderState(OrderInfoDTO order) throws Exception {
		if(OrderStatus.WAIT_FOR_PAY.equals(order.getOrderStatus())) {
			return waitForPayOrderState;
		} else if(OrderStatus.CANCELED.equals(order.getOrderStatus())) {
			return canceledOrderState;
		}
		return defaultOrderState;
	}

}
